﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using MMOArpgServer.Net;

namespace MMOArpgServer.Pool
{
    public class ClientPool
    {
        private static ClientPool _Instance;
        private static readonly object lockObj = new object();

        private Dictionary<int, ClientToken> _UserPool; 
        private Queue<ClientToken> _FreeClients = new Queue<ClientToken>();

        /// <summary>
        /// 通过角色的id储存链接，链接中含有AccoutID
        /// </summary>
        public Dictionary<int, ClientToken> UserPool
        {
            get
            {
                return _UserPool;
            }
        }

        protected ClientPool()
        {
            _UserPool = new Dictionary<int, ClientToken>();

        }
        public  static ClientPool GetInstance()
        {

            lock (lockObj)
            {
                if (_Instance == null)
                {
                    _Instance = new ClientPool();
                }
            }
            return _Instance;
        }

        public ClientToken GetClientByID(int userID)
        {
            return UserPool[userID];
        }
        public ClientToken GetFreeClientToken() {
            ClientToken temp;
            if (_FreeClients.Count > 0) {
                temp = _FreeClients.Dequeue();
            }
            else {
                temp = new ClientToken();
            }
            return temp;
        }

        public void AddClient(int userID, ClientToken clientToken)
        {
            UserPool.Add(userID, clientToken);
        }

        public void RemoveClient(int userID)
        {
            _FreeClients.Enqueue(UserPool[userID]);
            UserPool.Remove(userID);
        }
        public void RemoveNoID(ClientToken client) {
            _FreeClients.Enqueue(client);
        }
        public int GetClientCount()
        {
            return UserPool.Count;
        }
        /// <summary>
        /// 清除所有在线的用户。
        /// </summary>
        public void ClearAll() {

            foreach (var client in UserPool) {
                client.Value.DisConnect();
            }
        }

        public int GetClientID(ClientToken client) {
            foreach (var item in _UserPool) {
                if (item.Value==client) {
                    return item.Key;
                }
            }
            return -1;
        }
    }
}
